using Microsoft.EntityFrameworkCore;
using RiceShop.Models;
using RiceShop.Extensions;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using admin_webapi.Utils;

namespace RiceShop.Services
{
    /// <summary>
    /// 订单服务接口 - 定义了订单相关的所有业务操作
    /// </summary>
    public interface IOrderService
    {
        /// <summary>
        /// 创建订单 - 将购物车或直接购买的商品转化为订单
        /// </summary>
        /// <param name="request">创建订单请求，包含地址、商品、支付方式等信息</param>
        /// <returns>创建成功的订单对象</returns>
        Task<Order> CreateOrderAsync(CreateOrderRequest request);

        /// <summary>
        /// 获取订单列表 - 支持分页和状态筛选
        /// </summary>
        /// <param name="pageSize">每页数量</param>
        /// <param name="pageIndex">页码，从1开始</param>
        /// <param name="status">订单状态筛选条件，可为空</param>
        /// <returns>分页后的订单列表</returns>
        Task<PagedList<Order>> GetOrdersAsync(int pageSize, int pageIndex, OrderStatus? status);

        /// <summary>
        /// 获取订单详情 - 包含订单基本信息和商品列表
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <returns>订单详情响应对象</returns>
        Task<OrderDetailResponse> GetOrderDetailAsync(string orderNo);

        /// <summary>
        /// 取消订单 - 将待支付订单状态改为已取消
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <param name="reason">取消原因</param>
        Task CancelOrderAsync(string orderNo, string reason = "用户取消订单");

        /// <summary>
        /// 删除订单 - 从数据库中移除订单记录
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        Task DeleteOrderAsync(string orderNo);

        /// <summary>
        /// 确认收货 - 将订单状态从待收货改为待评价
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        Task ConfirmOrderAsync(string orderNo);

        /// <summary>
        /// 支付订单 - 生成支付信息，准备进行支付
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <returns>支付信息，包含支付链接等</returns>
        Task<RiceShop.Models.PaymentInfo> PayOrderAsync(string orderNo);

        /// <summary>
        /// 获取物流信息 - 查询订单的物流跟踪记录
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <returns>物流信息，包含物流单号、公司和跟踪记录</returns>
        Task<LogisticsInfo> GetLogisticsInfoAsync(string orderNo);

        /// <summary>
        /// 申请售后服务 - 提交售后申请
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <param name="request">售后申请信息</param>
        Task ApplyAfterServiceAsync(string orderNo, AfterServiceRequest request);

        /// <summary>
        /// 获取超时未支付的订单 - 用于自动取消超时订单
        /// </summary>
        /// <returns>超时未支付的订单列表</returns>
        Task<List<Order>> GetTimeoutOrdersAsync();

        /// <summary>
        /// 更新订单状态 - 修改订单状态并记录相关信息
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <param name="status">新的订单状态</param>
        /// <param name="transactionId">交易ID，支付成功时需要</param>
        Task UpdateOrderStatusAsync(string orderNo, OrderStatus status, string? transactionId = null);

        /// <summary>
        /// 根据订单号获取订单 - 查询完整的订单信息
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <returns>订单对象，不存在则返回null</returns>
        Task<Order?> GetOrderByNoAsync(string orderNo);

        /// <summary>
        /// 更新订单为已支付状态
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <param name="transactionId">微信支付交易号</param>
        Task UpdateOrderPayStatusAsync(string orderNo, string transactionId);

        /// <summary>
        /// 设置订单退款状态
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <param name="outRefundNo">退款单号</param>
        /// <param name="refundStatus">退款状态</param>
        Task SetOrderRefundStatusAsync(string orderNo, string outRefundNo, string refundStatus);

        /// <summary>
        /// 完成订单退款
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <param name="outRefundNo">退款单号</param>
        Task CompleteOrderRefundAsync(string orderNo, string outRefundNo);

        /// <summary>
        /// 根据订单号获取订单 - 查询完整的订单信息（别名方法）
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <returns>订单对象，不存在则返回null</returns>
        Task<Order?> GetOrderByOrderNoAsync(string orderNo);

        /// <summary>
        /// 获取用户订单数量
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>订单数量</returns>
        Task<int> GetOrderCountByUserIdAsync(long userId);
    }

    /// <summary>
    /// 订单服务实现类 - 实现了IOrderService接口定义的所有订单业务逻辑
    /// </summary>
    public class OrderService : IOrderService
    {
        // 依赖注入的服务和组件
        private readonly ApplicationDbContext _context; // 数据库上下文
        private readonly ICartService _cartService; // 购物车服务
        private readonly IGoodService _goodService; // 商品服务
        private readonly ICouponService _couponService; // 优惠券服务
        private readonly IAddressService _addressService; // 地址服务
        private readonly IHttpContextAccessor _httpContextAccessor; // HTTP上下文访问器，用于获取当前用户信息
        private readonly PaylinksConfig _config; // 支付配置

        /// <summary>
        /// 构造函数 - 依赖注入所需的服务
        /// </summary>
        /// <param name="context">数据库上下文</param>
        /// <param name="cartService">购物车服务</param>
        /// <param name="goodService">商品服务</param>
        /// <param name="couponService">优惠券服务</param>
        /// <param name="addressService">地址服务</param>
        /// <param name="httpContextAccessor">HTTP上下文访问器</param>
        /// <param name="config">支付配置选项</param>
        public OrderService(
            ApplicationDbContext context,
            ICartService cartService,
            IGoodService goodService,
            ICouponService couponService,
            IAddressService addressService,
            IHttpContextAccessor httpContextAccessor,
            IOptions<PaylinksConfig> config)
        {
            _context = context;
            _cartService = cartService;
            _goodService = goodService;
            _couponService = couponService;
            _addressService = addressService;
            _httpContextAccessor = httpContextAccessor;
            _config = config.Value;
            _couponService = couponService;
            _addressService = addressService;
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 获取订单列表 - 实现分页和状态筛选功能
        /// </summary>
        /// <param name="pageSize">每页数量</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="status">订单状态筛选</param>
        /// <returns>分页后的订单列表</returns>
        public async Task<PagedList<Order>> GetOrdersAsync(int pageSize, int pageIndex, OrderStatus? status)
        {
            // 创建初始查询
            var query = _context.Orders.AsQueryable();

            // 如果指定了状态，添加状态筛选条件
            if (status.HasValue)
                query = query.Where(o => o.Status == status.Value);

            // 计算总记录数
            var total = await query.CountAsync();

            // 查询分页数据，包含订单项，并按创建时间倒序排序
            var items = await query
                .Include(o => o.Items) // 加载订单商品项
                .OrderByDescending(o => o.CreateTime) // 按创建时间倒序
                .Skip((pageIndex - 1) * pageSize) // 跳过前面页的数据
                .Take(pageSize) // 获取当前页数据
                .ToListAsync();

            // 返回分页结果
            return new PagedList<Order>(items, total, pageIndex, pageSize);
        }

        /// <summary>
        /// 获取订单详情 - 查询订单及其商品信息
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <returns>订单详情响应对象</returns>
        public async Task<OrderDetailResponse> GetOrderDetailAsync(string orderNo)
        {
            // 查询订单，包含订单商品项
            var order = await _context.Orders
                .Include(o => o.Items)
                .FirstOrDefaultAsync(o => o.OrderNo == orderNo);

            // 如果订单不存在，抛出异常
            if (order == null)
                throw new NotFoundException("订单不存在");

            // 构建并返回订单详情响应
            return new OrderDetailResponse
            {
                Order = order,
                Goods = order.Items.ToList()
            };
        }

        /// <summary>
        /// 创建订单 - 处理订单创建的完整流程
        /// </summary>
        /// <param name="request">创建订单请求</param>
        /// <returns>创建成功的订单</returns>
        public async Task<Order> CreateOrderAsync(CreateOrderRequest request)
        {
            // 获取当前用户ID，如果未登录则抛出异常
            var userId = _httpContextAccessor.HttpContext?.User.GetUserId() ??
                throw new UnauthorizedAccessException("用户未登录");

            // 1. 基础验证 - 确保订单包含商品
            if (request.Items == null || !request.Items.Any())
                throw new ArgumentException("订单商品不能为空");

            // 2. 验证地址 - 确保收货地址存在
            var address = await _context.Addresses
                .FirstOrDefaultAsync(a => a.Id == request.AddressId);

            if (address == null)
                throw new ArgumentException("收货地址不存在");

            // 3. 生成订单号 - 使用时间戳和随机数
            string orderNo = GenerateOrderNo();

            // 4. 校验商品库存并计算金额
            decimal totalAmount = 0;
            var orderItems = new List<OrderGoods>();

            // 遍历处理每个商品项
            foreach (var item in request.Items)
            {
                // 获取商品信息，包含SKU数据
                var good = await _context.Goods
                    .Include(g => g.Skus)
                    .FirstOrDefaultAsync(g => g.SpuId == item.SpuId);

                if (good == null)
                    throw new ArgumentException($"商品不存在: {item.SpuId}");

                // 处理单规格商品
                if (good.OpenSpec != 1)
                {
                    // 检查库存是否充足
                    if (good.SpuStockQuantity < item.Quantity)
                        throw new ArgumentException($"商品库存不足: {good.Title ?? "未知商品"}");

                    // 创建订单商品项
                    var orderItem = new OrderGoods
                    {
                        OrderNo = orderNo,
                        SpuId = good.SpuId,
                        GoodTitle = item.GoodTitle ?? good.Title ?? "未知商品",
                        SalePrice = item.SalePrice,
                        PrimaryImage = good.PrimaryImage ?? "",
                        Quantity = item.Quantity,
                        SkuId = item.SkuId,
                        SpecValues = item.SpecValues ?? "单规格",
                        Code = item.Code ?? good.SpuNo,
                        Unit = item.Unit ?? "件",
                        LinePrice = item.LinePrice ?? good.LinePrice,
                        CreateTime = DateTime.Now
                    };

                    orderItems.Add(orderItem);
                    totalAmount += orderItem.SalePrice * item.Quantity;

                    // 更新商品库存
                    good.SpuStockQuantity -= item.Quantity;
                }
                // 处理多规格商品
                else
                {
                    // 多规格商品必须指定 SKU
                    if (item.SkuId == 0)
                        throw new ArgumentException($"多规格商品必须指定SKU: {good.Title ?? "未知商品"}");

                    // 查找对应的SKU
                    var sku = good.Skus.FirstOrDefault(s => s.SkuId == item.SkuId);
                    if (sku == null)
                        throw new ArgumentException($"商品SKU不存在: {item.SkuId}");

                    // 检查SKU库存是否充足
                    if (sku.Stock < item.Quantity)
                        throw new ArgumentException($"商品规格库存不足: {good.Title ?? "未知商品"} - {sku.SpecValues}");

                    // 创建订单商品项
                    var orderItem = new OrderGoods
                    {
                        OrderNo = orderNo,
                        SpuId = good.SpuId,
                        GoodTitle = item.GoodTitle ?? good.Title ?? "未知商品",
                        SalePrice = item.SalePrice,
                        PrimaryImage = good.PrimaryImage ?? "",
                        Quantity = item.Quantity,
                        SkuId = sku.SkuId,
                        SpecValues = item.SpecValues ?? sku.SpecValues ?? "",
                        Code = item.Code ?? sku.Code,
                        Unit = item.Unit ?? "件",
                        LinePrice = item.LinePrice ?? sku.LinePrice,
                        CreateTime = DateTime.Now
                    };

                    orderItems.Add(orderItem);
                    totalAmount += orderItem.SalePrice * item.Quantity;

                    // 更新SKU库存
                    sku.Stock -= item.Quantity;
                }
            }

            // 5. 验证优惠券(如果使用)
            decimal couponAmount = 0;
            if (request.CouponId.HasValue)
            {
                // 获取用户优惠券
                var userCoupon = await _couponService.GetUserCouponAsync(request.CouponId.Value);
                if (userCoupon == null)
                    throw new ArgumentException("优惠券不存在或已使用");

                // 检查优惠券是否可用
                if (userCoupon.Status != 0) // 0:未使用
                    throw new ArgumentException("优惠券已使用");

                // 检查优惠券是否过期
                var coupon = await _context.Coupons.FindAsync(userCoupon.CouponId);
                if (coupon == null)
                    throw new ArgumentException("优惠券不存在");

                if (coupon.Status != 1 || // 1:生效中
                    DateTime.Now < coupon.StartTime ||
                    DateTime.Now > coupon.EndTime)
                    throw new ArgumentException("优惠券已过期");

                // 检查订单金额是否满足使用门槛
                if (totalAmount < coupon.MinAmount)
                    throw new ArgumentException($"订单金额未满{coupon.MinAmount}元，不可使用该优惠券");

                couponAmount = coupon.Amount;
            }

            // 6. 创建订单对象
            var order = new Order
            {
                OrderNo = orderNo,
                UserId = userId,
                Status = OrderStatus.Pending, // 初始状态为待支付
                PaymentType = request.PaymentType,
                Source = request.Source,
                ReceiverName = address.ReceiverName,
                PhoneNumber = address.PhoneNumber,
                Province = address.Province,
                City = address.City,
                District = address.District,
                DetailAddress = address.DetailAddress,
                TotalAmount = totalAmount, // 商品总价
                Freight = 0, // 运费，可以根据实际需求计算
                DiscountAmount = couponAmount, // 优惠金额
                PayAmount = totalAmount - couponAmount, // 实付金额
                CouponId = request.CouponId,
                Remark = request.Remark,
                Items = orderItems, // 订单商品项
                AddressId = address.Id,
                CreateTime = DateTime.Now
            };

            // 7. 保存订单并处理相关业务，使用事务确保数据一致性
            using var transaction = await _context.Database.BeginTransactionAsync();
            try
            {
                // 添加订单到数据库
                _context.Orders.Add(order);

                // 如果是购物车下单，清空该用户的购物车
                if (request.Source == 1)
                {
                    await _cartService.ClearCartAsync(userId);
                }

                // 如果使用了优惠券，标记优惠券为已使用
                if (request.CouponId.HasValue)
                {
                    await _couponService.UseCouponAsync(userId, request.CouponId.Value);
                }

                // 保存所有更改
                await _context.SaveChangesAsync();
                // 提交事务
                await transaction.CommitAsync();

                return order;
            }
            catch
            {
                // 发生异常时回滚事务
                await transaction.RollbackAsync();
                throw;
            }
        }

        /// <summary>
        /// 生成订单号 - 使用时间戳和随机数创建唯一订单号
        /// </summary>
        /// <returns>生成的订单号</returns>
        private string GenerateOrderNo()
        {
            // 生成订单号：时间戳(年月日时分秒) + 4位随机数
            return DateTime.Now.ToString("yyyyMMddHHmmss") +
                   Random.Shared.Next(1000, 9999).ToString();
        }

        /// <summary>
        /// 取消订单 - 将待支付订单状态改为已取消
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <param name="reason">取消原因</param>
        public async Task CancelOrderAsync(string orderNo, string reason = "用户取消订单")
        {
            // 查找订单 - 使用OrderNo查询而非FindAsync
            var order = await _context.Orders
                .FirstOrDefaultAsync(o => o.OrderNo == orderNo);
        
            if (order == null)
                throw new NotFoundException("订单不存在");

            // 检查订单状态是否可取消
            if (order.Status != OrderStatus.Pending)
                throw new Exception("当前订单状态不可取消");

            // 更新订单状态为已取消
            order.Status = OrderStatus.Cancelled;
            order.StatusDesc = reason;
            order.UpdateTime = DateTime.Now;
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 确认收货 - 将订单状态从待收货改为待评价
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        public async Task ConfirmOrderAsync(string orderNo)
        {
            // 查找订单 - 使用OrderNo查询而非FindAsync
            var order = await _context.Orders
                .FirstOrDefaultAsync(o => o.OrderNo == orderNo);
        
            if (order == null)
                throw new Exception("订单不存在");

            // 检查订单状态是否可确认收货
            if (order.Status != OrderStatus.Receiving)
                throw new Exception("当前订单状态不可确认收货");

            // 更新订单状态为待评价
            order.Status = OrderStatus.Evaluating;
            order.StatusDesc = "已确认收货";
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 获取物流信息 - 查询订单的物流跟踪记录
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <returns>物流信息</returns>
        public async Task<LogisticsInfo> GetLogisticsInfoAsync(string orderNo)
        {
            // 此方法尚未实现，返回一个已完成的任务并抛出NotImplementedException
            await Task.CompletedTask;
            throw new NotImplementedException();
        }

        /// <summary>
        /// 申请售后服务 - 提交售后申请
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <param name="request">售后申请信息</param>
        public async Task ApplyAfterServiceAsync(string orderNo, AfterServiceRequest request)
        {
            // 此方法尚未实现，返回一个已完成的任务并抛出NotImplementedException
            await Task.CompletedTask;
            throw new NotImplementedException();
        }

        /// <summary>
        /// 删除订单 - 从数据库中移除订单记录
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        public async Task DeleteOrderAsync(string orderNo)
        {
            // 查找订单 - 使用OrderNo查询而非FindAsync
            var order = await _context.Orders
                .FirstOrDefaultAsync(o => o.OrderNo == orderNo);
        
            if (order == null)
                throw new NotFoundException("订单不存在");

            // 从数据库中移除订单
            _context.Orders.Remove(order);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 支付订单 - 生成支付信息，准备进行支付
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <returns>支付信息，包含支付链接等</returns>
        public async Task<RiceShop.Models.PaymentInfo> PayOrderAsync(string orderNo)
        {
            // 查询订单，包含订单商品项
            var order = await _context.Orders
                .Include(o => o.Items)
                .FirstOrDefaultAsync(o => o.OrderNo == orderNo);

            if (order == null)
                throw new NotFoundException("订单不存在");

            // 检查订单状态是否可支付
            if (order.Status != OrderStatus.Pending)
                throw new Exception("订单状态不正确，只有待支付订单可以支付");

            // 获取用户OpenId（假设已经存储在用户表中）
            var user = await _context.Users.FindAsync(order.UserId);
            if (user == null)
                throw new Exception("用户不存在");

            try
            {
                // 调用微信支付统一下单API
                // total_fee 是微信支付必填参数，单位为分（int）
                int totalFee = (int)(order.PayAmount * 100); // 金额元转分
                // 这里应该调用微信支付API，传递total_fee参数
                // 示例：var prepayId = await WxPayApi.UnifiedOrderAsync(..., total_fee: totalFee, ...);
                var prepayId = $"wx_prepay_{order.OrderNo}_{DateTime.Now.Ticks}";

                // 构建签名字符串
                string timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
                string nonceStr = Guid.NewGuid().ToString("N");
                string package = $"prepay_id={prepayId}";
                
                // 按微信支付规则拼接签名字符串
                string message = $"{_config.WeChatPay.AppId}\n{timestamp}\n{nonceStr}\n{package}\n";
                
                // 使用商户私钥进行签名
                string paySign = SignatureHelper.SignWithRsa(message, _config.WeChatPay.MchPrivateKey);

                var paymentInfo = new RiceShop.Models.PaymentInfo
                {
                    OrderNo = order.OrderNo,
                    Amount = order.PayAmount,
                    PaymentUrl = $"weixin://wxpay/bizpayurl?pr={order.OrderNo}",
                    Package = package,
                    TimeStamp = timestamp,
                    NonceStr = nonceStr,
                    SignType = "RSA",
                    PaySign = paySign
                };

                // 更新订单支付信息
                order.UpdateTime = DateTime.Now;
                await _context.SaveChangesAsync();

                return paymentInfo;
            }
            catch (Exception ex)
            {
                throw new Exception($"创建支付订单失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取超时未支付的订单 - 用于自动取消超时订单
        /// </summary>
        /// <returns>超时未支付的订单列表</returns>
        public async Task<List<Order>> GetTimeoutOrdersAsync()
        {
            // 获取30分钟前创建但未支付的订单
            var timeoutPoint = DateTime.Now.AddMinutes(-30);

            return await _context.Orders
                .Where(o => o.Status == OrderStatus.Pending
                    && o.CreateTime < timeoutPoint)
                .ToListAsync();
        }

        /// <summary>
        /// 更新订单状态 - 修改订单状态并记录相关信息
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <param name="status">新的订单状态</param>
        /// <param name="transactionId">交易ID，支付成功时需要</param>
        public async Task UpdateOrderStatusAsync(string orderNo, OrderStatus status, string? transactionId = null)
        {
            // 查找订单 - 使用OrderNo查询而非FindAsync
            var order = await _context.Orders
                .FirstOrDefaultAsync(o => o.OrderNo == orderNo)
                ?? throw new NotFoundException("订单不存在");

            // 更新订单状态
            order.Status = status;
            order.UpdateTime = DateTime.Now;

            // 根据不同状态设置不同的附加信息
            switch (status)
            {
                case OrderStatus.Shipping:
                    order.PayTime = DateTime.Now;
                    order.StatusDesc = "支付成功";
                    order.TransactionId = transactionId;
                    break;
                case OrderStatus.Cancelled:
                    order.StatusDesc = "订单已取消";
                    break;
                    // ... 其他状态处理
            }

            // 保存更改
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 根据订单号获取订单 - 查询完整的订单信息
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <returns>订单对象，不存在则返回null</returns>
        public async Task<Order?> GetOrderByNoAsync(string orderNo)
        {
            // 查询订单，包含订单商品项
            return await _context.Orders
                .Include(o => o.Items)
                .FirstOrDefaultAsync(o => o.OrderNo == orderNo);
        }

        /// <summary>
        /// 更新订单为已支付状态
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <param name="transactionId">微信支付交易号</param>
        public async Task UpdateOrderPayStatusAsync(string orderNo, string transactionId)
        {
            var order = await _context.Orders
                .FirstOrDefaultAsync(o => o.OrderNo == orderNo)
                ?? throw new NotFoundException("订单不存在");

            // 如果订单已经是已支付状态，直接返回
            if (order.Status == OrderStatus.Shipping)
            {
                return;
            }

            // 更新订单状态为已支付
            order.Status = OrderStatus.Shipping; // 假设支付成功后状态为"待发货"
            order.PayTime = DateTime.Now;
            order.StatusDesc = "支付成功";
            order.TransactionId = transactionId;
            order.UpdateTime = DateTime.Now;

            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 设置订单退款状态
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <param name="outRefundNo">退款单号</param>
        /// <param name="refundStatus">退款状态</param>
        public async Task SetOrderRefundStatusAsync(string orderNo, string outRefundNo, string refundStatus)
        {
            var order = await _context.Orders
                .FirstOrDefaultAsync(o => o.OrderNo == orderNo)
                ?? throw new NotFoundException("订单不存在");

            // 根据退款状态更新订单状态
            if (refundStatus == "SUCCESS")
            {
                // 退款成功，更新订单状态为已退款
                order.Status = OrderStatus.Cancelled;
                order.StatusDesc = $"已退款：{outRefundNo}";
            }
            else if (refundStatus == "PROCESSING")
            {
                // 退款处理中，记录状态但不改变订单状态
                order.StatusDesc = $"退款处理中：{outRefundNo}";
            }

            order.UpdateTime = DateTime.Now;
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 完成订单退款
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <param name="outRefundNo">退款单号</param>
        public async Task CompleteOrderRefundAsync(string orderNo, string outRefundNo)
        {
            var order = await _context.Orders
                .FirstOrDefaultAsync(o => o.OrderNo == orderNo)
                ?? throw new NotFoundException("订单不存在");

            // 更新订单状态为已退款（取消）
            order.Status = OrderStatus.Cancelled;
            order.StatusDesc = $"退款成功：{outRefundNo}";
            order.UpdateTime = DateTime.Now;

            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 根据订单号获取订单 - 查询完整的订单信息（别名方法）
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <returns>订单对象，不存在则返回null</returns>
        public async Task<Order?> GetOrderByOrderNoAsync(string orderNo)
        {
            return await GetOrderByNoAsync(orderNo);
        }

        /// <summary>
        /// 获取用户订单数量
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>订单数量</returns>
        public async Task<int> GetOrderCountByUserIdAsync(long userId)
        {
            try
            {
                var count = await _context.Orders
                    .Where(o => o.UserId == userId)
                    .CountAsync();
                    
                return count;
            }
            catch (Exception ex)
            {
                // 记录错误日志
                throw new Exception($"获取用户订单数量失败，用户ID: {userId}", ex);
            }
        }
    }

    /// <summary>
    /// 自定义异常类 - 表示请求的资源不存在
    /// </summary>
    [Serializable]
    public class NotFoundException : Exception
    {
        public NotFoundException()
        {
        }

        public NotFoundException(string? message) : base(message)
        {
        }

        public NotFoundException(string? message, Exception? innerException) : base(message, innerException)
        {
        }
    }

    /// <summary>
    /// 分页列表类 - 用于返回分页查询结果
    /// </summary>
    /// <typeparam name="T">列表项类型</typeparam>
    public class PagedList<T>
    {
        /// <summary>
        /// 当前页的数据项
        /// </summary>
        public List<T> Items { get; }

        /// <summary>
        /// 总记录数
        /// </summary>
        public int Total { get; }

        /// <summary>
        /// 当前页码
        /// </summary>
        public int PageIndex { get; }

        /// <summary>
        /// 每页记录数
        /// </summary>
        public int PageSize { get; }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="items">当前页数据</param>
        /// <param name="total">总记录数</param>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">每页记录数</param>
        public PagedList(List<T> items, int total, int pageIndex, int pageSize)
        {
            Items = items;
            Total = total;
            PageIndex = pageIndex;
            PageSize = pageSize;
        }
    }

    /// <summary>
    /// 订单详情响应类 - 包含订单信息、商品列表和物流信息
    /// </summary>
    public class OrderDetailResponse
    {
        /// <summary>
        /// 订单基本信息
        /// </summary>
        public required Order Order { get; set; }

        /// <summary>
        /// 订单商品列表
        /// </summary>
        public required List<OrderGoods> Goods { get; set; }

        /// <summary>
        /// 物流信息，可为空
        /// </summary>
        public LogisticsInfo? Logistics { get; set; }
    }

    /// <summary>
    /// 创建订单请求模型 - 包含创建订单所需的所有信息
    /// </summary>
    public class CreateOrderRequest
    {
        /// <summary>
        /// 收货地址ID - 用于获取收货人信息
        /// </summary>
        public long AddressId { get; set; }

        /// <summary>
        /// 订单商品列表 - 包含要购买的商品信息
        /// </summary>
        public required List<CartItem> Items { get; set; }

        /// <summary>
        /// 支付方式 - 1:微信支付 2:支付宝支付
        /// </summary>
        public byte PaymentType { get; set; }

        /// <summary>
        /// 订单备注 - 买家留言
        /// </summary>
        public string Remark { get; set; } = string.Empty;

        /// <summary>
        /// 优惠券ID - 用于计算优惠金额，可为空
        /// </summary>
        public long? CouponId { get; set; }

        /// <summary>
        /// 来源 - 1:购物车 2:立即购买
        /// </summary>
        public byte Source { get; set; }
    }

    /// <summary>
    /// 购物车项模型 - 用于创建订单时传递商品信息
    /// </summary>
    public class CartItem
    {
        /// <summary>
        /// 购物车ID - 购物车中的唯一标识
        /// </summary>
        public long Id { get; set; }

        /// <summary>
        /// 用户ID - 购物车所属用户
        /// </summary>
        public long UserId { get; set; }

        /// <summary>
        /// 商品SPU ID
        /// </summary>
        public long SpuId { get; set; }

        /// <summary>
        /// 商品标题
        /// </summary>
        public string? GoodTitle { get; set; }

        /// <summary>
        /// 商品单价
        /// </summary>
        public decimal SalePrice { get; set; }

        /// <summary>
        /// 商品数量
        /// </summary>
        public int Quantity { get; set; }

        /// <summary>
        /// 是否选中
        /// </summary>
        public bool IsSelected { get; set; }

        /// <summary>
        /// SKU ID
        /// </summary>
        public long SkuId { get; set; }

        /// <summary>
        /// 库存数量
        /// </summary>
        public int StockQuantity { get; set; }

        /// <summary>
        /// 规格值组合
        /// </summary>
        public string? SpecValues { get; set; }

        /// <summary>
        /// 商品编码
        /// </summary>
        public string? Code { get; set; }

        /// <summary>
        /// 商品单位
        /// </summary>
        public string? Unit { get; set; }

        /// <summary>
        /// 划线价
        /// </summary>      
        public decimal? LinePrice { get; set; }
    }

    public class AfterServiceRequest
    {
        public int Type { get; set; }
        public required string Reason { get; set; }
        public required string Description { get; set; }
        public required List<string> Images { get; set; }
    }

    public class LogisticsInfo
    {
        public required string LogisticsNo { get; set; }
        public required string LogisticsCompany { get; set; }
        public required List<LogisticsTrace> Traces { get; set; }
    }

    public class LogisticsTrace
    {
        public DateTime Time { get; set; }
        public required string Description { get; set; }
    }
}